#ifndef BASE_SYSTEM_LOG_IO_INCLUDE_IO_FILE_OUTPUT_STRATEGY_H
#define BASE_SYSTEM_LOG_IO_INCLUDE_IO_FILE_OUTPUT_STRATEGY_H

#include <mutex>
#include <string>
#include <unistd.h>
#include "i_output_strategy.h"
#include "system_log_config.h"

namespace Base {
namespace SystemLog {

// 前置声明
class AsyncFsync;

struct FileOutputOptions {
    std::string filePathPattern = "logs/log_%Y%m%d_%H%M%S.log";
    size_t maxFileSize = 100 * 1024 * 1024; // 100MB
    std::chrono::seconds rollInterval = std::chrono::hours(24); // 每天滚动
    bool useAsyncFsync = true; // 是否使用异步fsync，默认启用
    uint32_t asyncFsyncIntervalMs = DEFAULT_ASYNC_FSYNC_INTERVAL_MS; // 异步fsync间隔，默认5秒
};

class FileOutputStrategy  : public IOutputStrategy {
public:
    explicit FileOutputStrategy(const FileOutputOptions &options);
    ~FileOutputStrategy() override;
    ErrCode Write(const char* data, size_t len) override;
    ErrCode Flush() override;
    ErrCode Close() override;

    std::string GetName() const override {
        return "FileOutput";
    }

    std::string GetCurrentFilePath() const;
    
    /**
     * 强制立即同步文件到磁盘
     */
    ErrCode ForceSync();

protected:
    virtual ErrCode OpenFile();
    virtual ErrCode CloseCurrentFile();
    virtual ErrCode WriteToFile(const char* data, size_t len);
    virtual ErrCode FlushFile();
    ErrCode RollFileIfNeeded(size_t newDataSize);
    std::string GenerateFileName() const;

    FileOutputOptions fileOptions_;
    int fileDescriptor_ = -1;
    size_t currentSize_ = 0;
    std::chrono::system_clock::time_point lastRollTime_;
    mutable std::mutex mutex_;
    AsyncFsync* asyncFsync_ = nullptr; // AsyncFsync实例的引用
};
} // namespace SystemLog
} // namespace Base

#endif // BASE_SYSTEM_LOG_IO_INCLUDE_IO_FILE_OUTPUT_STRATEGY_H